﻿using InControls.PLC.FX;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using commandDemo;
using HalconDotNet;
using ProducerConsumeClass;
using System.Threading;
using ImagePro;

namespace PLCDEMO
{
    

    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
            CreateHalconWindow();
        }

        public Form2(HObject dstImage)
        {
            DstImage = dstImage;
        }

        //PLC串口   
        #region 变量初始化
        SerialPort serialPort1 = new SerialPort("COM2", 115200, Parity.None, 8, StopBits.One); public string[] ArryPort = SerialPort.GetPortNames();
        //声明委托变量
        public Displaydelegate disp_delegate; 
        //委托方法及其输入参数
        public delegate void Displaydelegate(byte[] InputBuf); 
        Byte[] OutputBuf = new Byte[512];
        ASCIIEncoding encoding = new ASCIIEncoding();
        private HObject DstImage;
        private static bool setStart = false;

        public static bool SetStart{ set { setStart = value; } get { return setStart; } }
        //离线数据
        XML_Data XML_DATA;
        private bool m_btnState;
        public HObject Image;
        public delegate void  Mydelegate();
        private Mydelegate my;
        Thread ProcessThread;
        //图片的窗口句柄
        public static HTuple WindowID;
        public static int low ;
        public static int high;
        private long count = 0;
        public HTuple image_width, image_height;
        //处理事件 委托的实体事件
        #endregion


        private void Form2_Load(object sender, EventArgs e)
        {
            Form1 fr1 = Form1.CreateInstrance();
            fr1.Show();

            Form3 fr3 = new Form3();
            fr3.Show();
            serial_init();
            data_view_load();

            my += DataChangeEventArgs;
            my += outDataRecord;

            low = trackBar2.Value;
            high = trackBar3.Value;
            //委托的方法
        }

        #region 获取相机的句柄
        public static HTuple cameraCatchEnable
        {
            get { return WindowID; }
        }
        #endregion

        private void serial_init()
        {
            this.SetDesktopLocation(800, 100);
            disp_delegate = new Displaydelegate(DispUI);

            //控件参数初始化
            toolStripStatusLabel2.Text = "V1.0";

            //获取已经识别到的串口
            string[] str = SerialPort.GetPortNames();

            //_FxSerial.Start();
            if (str == null)
            {
                MessageBox.Show("串口没有存在");
                return;
            }

            //添加串口
            foreach (string s in str)
            {
                comboBoxCom.Items.Add(s);
            }

            //设置默认串口选项
            comboBoxCom.SelectedIndex = -1;
            /*------波特率设置-------*/
            comboBox_datasort.SelectedIndex = 0;

            //接收数据的触发的事件
            serialPort1.DataReceived += new SerialDataReceivedEventHandler(Comm_DataReceived);

            //准备就绪              
            serialPort1.DtrEnable = true;
            serialPort1.RtsEnable = true;
            //设置数据读取超时为1秒
            serialPort1.ReadTimeout = 1000;
            serialPort1.Close();

            // radioButton1 Appearance
            this.radioButton1.Appearance = System.Windows.Forms.Appearance.Button;
            this.radioButton1.Checked = false;
            this.m_btnState = this.radioButton1.Checked;

        }

        private void data_view_load()
        {
            Datedemo dd = new Datedemo();
            //dataGridView1.DataSource = dd.SetTable();

            //XML_DATA = dd.XML_Data_Init("init");
            XML_DATA = dd.XML_Data_Init2<XML_Data>("init");
            textBox1.DataBindings.Add("Text", XML_DATA, "IntValue", false, DataSourceUpdateMode.OnPropertyChanged);
            textBox2.DataBindings.Add("Text", XML_DATA, "StrValue", false, DataSourceUpdateMode.OnPropertyChanged);
            textBox3.DataBindings.Add("Text", XML_DATA, "ThresholdLowTrack", false, DataSourceUpdateMode.Never);
            trackBar2.DataBindings.Add("Value", XML_DATA, "ThresholdLowTrack", false, DataSourceUpdateMode.OnPropertyChanged);
            textBox4.DataBindings.Add("Text", XML_DATA, "ThresholdHighTrack", false, DataSourceUpdateMode.Never);
            trackBar3.DataBindings.Add("Value", XML_DATA, "ThresholdHighTrack", false, DataSourceUpdateMode.OnPropertyChanged);
        }

        public void CreateHalconWindow()
        {
            HTuple FatherWindow = hw2.HalconWindow;
            //设置窗口的背景颜色
            HOperatorSet.SetWindowAttr("background_color", "black");
            HOperatorSet.OpenWindow(0, 0, this.hw2.Width, this.hw2.Height, FatherWindow, "visible", "", out WindowID);

        }
        private void button_serial_Click(object sender, EventArgs e)
        {
            if (!serialPort1.IsOpen)//串口处于关闭状态
            {

                try
                {
                    string strSerialName = comboBoxCom.SelectedItem.ToString();
                    string DataSort = comboBox_datasort.SelectedIndex.ToString();
                    //打开串口
                    //串口的打开会引起线程的同步线程
                    serialPort1.PortName = strSerialName;        
                    serialPort1.Open();
                    button_serial.Text = "关闭串口";

                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("Error:" + ex.Message, "Error");

                    return;
                }
            }
            else //串口处于打开状态
            {
                serialPort1.Close();//关闭串口
                button_serial.Text = "打开串口";
                toolStripStatusLabel2.Text = "";
            }
        }


        private void comboBox1_DropDown(object sender, EventArgs e)
        {

            foreach (string vportname in SerialPort.GetPortNames())
            {
                //this.comboBoxCom.Items += this.comboBoxCom.Items + vportname + "/r/n";
            }
        }

        void Comm_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
          
            try
            {
                int n = serialPort1.BytesToRead;
                Byte[] InputBuf = new Byte[n];
                serialPort1.Read(InputBuf, 0, n);           //读取缓冲区的数据直到“}”即0x7D为结束符  
                
                // InputBuf = UnicodeEncoding.Default.GetBytes(strRD);             //将得到的数据转换成byte的格式  
                //假同步
                System.Threading.Thread.Sleep(30);
                this.Invoke(disp_delegate, InputBuf);

            }
            catch (TimeoutException ex)         //超时处理  
            {
                MessageBox.Show(ex.ToString());
            }
        }

        public void DispUI(byte[] InputBuf)
        {
            //textBox1.Text = Convert.ToString(InputBuf);  
       
            if (comboBox_datasort.SelectedIndex == 0)
            {
                try
                {
                    
                    Textbox_receive.Text += encoding.GetString(InputBuf) + "\r\n";

                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message, "你波特率是不是有问题？？？");
                    return;
                }

                Textbox_receive.SelectionStart = Textbox_receive.Text.Length;
                Textbox_receive.ScrollToCaret();//滚动到光标处
                serialPort1.DiscardInBuffer(); //清空SerialPort控件的Buffer 
            }

            else //接收格式为HEX
            {
                try
                {
                    Char[] c = Encoding.ASCII.GetChars(InputBuf);
                    foreach (char letter in c)
                    {
                        // Get the integral value of the character.
                        int value = Convert.ToInt32(letter);
                        // Convert the decimal value to a hexadecimal value in string form.
                        string hexOutput = String.Format("{0:X}", value);
                        Textbox_receive.AppendText(hexOutput + " ");
                        Textbox_receive.SelectionStart = Textbox_receive.Text.Length;
                        Textbox_receive.ScrollToCaret();//滚动到光标处
                                                        //textBoxReceive.Text += hexOutput + " ";
                        serialPort1.DiscardInBuffer(); //清空SerialPort控件的Buffer 

                    }

                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error");
                    Textbox_receive.Text = "";//清空
                }
            }


        }

        //private void Form2_FormClosing(object sender, FormClosingEventArgs e)
        //{
        //    e.Cancel = true;
        //}

        private void button1_Click(object sender, EventArgs e)
        {
            comboBoxCom.Text = "";
            comboBoxCom.Items.Clear();

            string[] str = SerialPort.GetPortNames();
            if (str == null)
            {
                MessageBox.Show("本机没有串口！", "Error");
                return;
            }
            //添加串口
            foreach (string s in str)
            {
                comboBoxCom.Items.Add(s);
            }
            //设置默认串口选项
            comboBoxCom.SelectedIndex = -1;
        }

        private void button_cmd_Click(object sender, EventArgs e)
        {
            if (!serialPort1.IsOpen)
            {
                MessageBox.Show("请先打开串口", "Error");
                return;
            }


        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            toolStripStatus_time.Text = DateTime.Now.ToString();           
            
        }

        private void button_plc_test_Click(object sender, EventArgs e)
        {
         
            serialPort1.Write("hello");
        }

        private void button_send_rst_Click(object sender, EventArgs e)
        {
            textBox_send.Text = "";
        }

        private void botton_receive_rst_Click(object sender, EventArgs e)
        {
            Textbox_receive.Text = "";
        }

        private void Textbox_receive_TextChanged(object sender, EventArgs e)
        {

        }


        private void button1_Click_2(object sender, EventArgs e)
        {
            commandDemo.Datedemo.XML_Data_Save("init", XML_DATA);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("数据是否重置", "提示", MessageBoxButtons.OKCancel);

            if (dr == DialogResult.OK)
            {
                //这里不能用 new 因为new了之后会出现句柄的地址发生变化
                //XML_DATA = new XML_Data();
                XML_DATA.ResetData();
                textBox1.DataBindings.Clear();
                textBox2.DataBindings.Clear();
                textBox3.DataBindings.Clear();
                trackBar2.DataBindings.Clear();
                textBox4.DataBindings.Clear();
                trackBar3.DataBindings.Clear();

                textBox1.DataBindings.Add("Text", XML_DATA, "IntValue", false, DataSourceUpdateMode.OnPropertyChanged);
                textBox2.DataBindings.Add("Text", XML_DATA, "StrValue", false, DataSourceUpdateMode.OnPropertyChanged);
                textBox3.DataBindings.Add("Text", XML_DATA, "ThresholdLowTrack", false, DataSourceUpdateMode.Never);
                trackBar2.DataBindings.Add("Value", XML_DATA, "ThresholdLowTrack", false, DataSourceUpdateMode.OnPropertyChanged);
                textBox4.DataBindings.Add("Text", XML_DATA, "ThresholdHighTrack", false, DataSourceUpdateMode.Never);
                trackBar3.DataBindings.Add("Value", XML_DATA, "ThresholdHighTrack", false, DataSourceUpdateMode.OnPropertyChanged);

                MessageBox.Show("重置成功");
            }
            else if (dr == DialogResult.Cancel)
            {
            }
           
        }


        private void radioButton1_Click(object sender, EventArgs e)
        {
            if (m_btnState == false)
            {

                this.radioButton1.Checked = true;
                this.m_btnState = true;

                //tempImage = Form1.Image;
            }
            else
            {
                this.radioButton1.Checked = false;
                this.m_btnState = false;
            }
        }



        public void showImage(Object image)
        {
            while(true)
            {
                if (image != null)
                {
                    HObject i = (HObject)image;
                    HOperatorSet.DispImage(i, WindowID);
                }
            }
        }

        //private void btn_lookPic_Click(object sender, EventArgs e)
        //{
        //    Form1 f1 = new Form1();
        //    f1.Show();
        //}

        public bool getM_btnState()
        {
            HOperatorSet.ClearWindow(WindowID);
            return m_btnState;
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {

        }

        private void Form2_FormClosing(object sender, FormClosingEventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
            if( Form1.video_enable == false )
            {
                MessageBox.Show("请打开相机！");
            }

            if (SetStart == false)
            {
                button3.Text = "停止处理";
                SetStart = true;
                ProcessThread = new Thread(() =>
                {
                    while(true)
                    {
                        my();
                        Thread.Sleep(20);
                    }
                });

                ProcessThread.Start();
            }
            else
            {
                ProcessThread.Abort();
                button3.Text = "开始处理";
                SetStart = false;
            }
        }

        private void textBox5_KeyPress(object sender, KeyPressEventArgs e)
        {
            //e.KeyChar = (Char)0;
        }

        private void textBox5_TextChanged(object sender, EventArgs e)
        {
            //textBox5.SelectionStart = textBox1.Text.Length;
            textBox5.ScrollToCaret();

            //textBox5.ScrollToCaret();
            //this.textBox5.Focus();//获取焦点
            //this.textBox5.Select(this.textBox5.TextLength, 0);//光标定位到文本最后
            //this.textBox5.ScrollToCaret();//滚动到光标处

            if (textBox5.TextLength > 2000)
            {
                string str = textBox5.Text.Substring(1000, 1000);
                textBox5.Text = str;
            }
        }

        public void DataChangeEventArgs()
        {
            if (this.trackBar2.InvokeRequired || this.trackBar3.InvokeRequired)
            {
                this.BeginInvoke(my);
            }
            else
            {
                low = trackBar2.Value;
                high = trackBar3.Value;
            }
            
        }

        public void outDataRecord()
        {
            if( textBox5.InvokeRequired)
            {
                this.BeginInvoke(my);
            }
            else
            {
                lock(new object())
                {
                    if (HDevelopExport.finish_status == true)
                    {
                        count++;
                        
                        textBox5.AppendText(count + " area:" + HDevelopExport.ar.ToString()+"   "+ HDevelopExport.ts.Milliseconds+ " \r\n ");
                        HDevelopExport.finish_status = false;
                    }
                }
            }
        }
    }

    //这个是事件触发的基类

}
